<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能客户关系管理助手 - 客户管理</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        :root {
            --primary: #4361ee;
            --secondary: #3f37c9;
            --accent: #4895ef;
            --dark: #1e1e2c;
            --darker: #14141f;
            --light: #f8f9fa;
            --success: #4caf50;
            --warning: #ff9800;
            --danger: #f44336;
            --gray: #6c757d;
            --border-radius: 8px;
            --transition: all 0.3s ease;
        }

        body {
            background-color: var(--darker);
            color: var(--light);
            display: flex;
            min-height: 100vh;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 250px;
            background-color: var(--dark);
            padding: 20px 0;
            height: 100vh;
            position: fixed;
            transition: var(--transition);
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
            z-index: 100;
        }

        .logo-container {
            display: flex;
            align-items: center;
            padding: 0 20px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 20px;
        }

        .logo {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, var(--accent), var(--primary));
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
        }

        .logo i {
            font-size: 20px;
        }

        .logo-text {
            font-size: 20px;
            font-weight: 700;
            background: linear-gradient(to right, var(--accent), var(--primary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .nav-links {
            list-style: none;
            padding: 0 15px;
        }

        .nav-links li {
            margin-bottom: 5px;
        }

        .nav-links a {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            text-decoration: none;
            color: rgba(255, 255, 255, 0.7);
            border-radius: var(--border-radius);
            transition: var(--transition);
        }

        .nav-links a:hover, .nav-links a.active {
            background-color: rgba(67, 97, 238, 0.2);
            color: var(--light);
        }

        .nav-links a i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }

        /* 主内容区样式 */
        .main-content {
            flex: 1;
            margin-left: 250px;
            padding: 20px;
            transition: var(--transition);
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .page-title {
            font-size: 24px;
            font-weight: 600;
            display: flex;
            align-items: center;
        }

        .page-title i {
            margin-right: 10px;
            color: var(--accent);
        }

        .user-actions {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-id-input {
            display: flex;
            gap: 10px;
            align-items: center;
            background-color: rgba(255, 255, 255, 0.08);
            padding: 8px 15px;
            border-radius: 30px;
        }

        .user-id-input input {
            background: transparent;
            border: none;
            color: white;
            font-size: 14px;
            width: 120px;
        }

        .user-id-input input::placeholder {
            color: rgba(255, 255, 255, 0.6);
        }

        .user-id-input button {
            background: var(--primary);
            border: none;
            color: white;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 12px;
            cursor: pointer;
        }

        .search-container {
            display: flex;
            flex-direction: column;
        }

        .search-container label {
            font-size: 14px;
            margin-bottom: 5px;
            opacity: 0.8;
        }

        .search-box {
            position: relative;
            height: 40px;
            display: flex;
            align-items: center;
        }

        .search-box input {
            background-color: rgba(255, 255, 255, 0.08);
            border: none;
            padding: 0 15px 0 40px;
            border-radius: 30px;
            color: var(--light);
            width: 250px;
            height: 100%;
            line-height: 1;
            margin: 0;
            transition: var(--transition);
        }

        .search-box input:focus {
            outline: none;
            background-color: rgba(255, 255, 255, 0.15);
            width: 300px;
        }

        .search-box i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: rgba(255, 255, 255, 0.5);
            margin: 0;
        }

        .user-profile {
            display: flex;
            align-items: center;
            background-color: rgba(255, 255, 255, 0.08);
            padding: 8px 15px;
            border-radius: 30px;
            cursor: pointer;
            transition: var(--transition);
        }

        .user-profile:hover {
            background-color: rgba(255, 255, 255, 0.15);
        }

        .user-profile img {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin-right: 10px;
            object-fit: cover;
        }

        /* 卡片样式 */
        .card {
            background-color: var(--dark);
            border-radius: var(--border-radius);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            margin-bottom: 25px;
            overflow: hidden;
        }

        .card-header {
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .card-title {
            font-size: 18px;
            font-weight: 600;
        }

        .card-body {
            padding: 20px;
        }

        /* 客户管理区域 */
        .customer-management {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .action-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .filters {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            margin-bottom: 20px;
            background-color: rgba(255, 255, 255, 0.05);
            padding: 15px;
            border-radius: var(--border-radius);
        }

        .filter-group {
            display: flex;
            flex-direction: column;
            min-width: 200px;
        }

        .filter-group label {
            font-size: 14px;
            margin-bottom: 5px;
            opacity: 0.8;
        }

        .filter-group select, .filter-group input {
            background-color: rgba(255, 255, 255, 0.08);
            border: none;
            padding: 10px 15px;
            border-radius: var(--border-radius);
            color: var(--light);
        }

        .filter-group select:focus, .filter-group input:focus {
            outline: none;
            background-color: rgba(255, 255, 255, 0.12);
        }

        /* 表格样式 */
        .table-container {
            overflow-x: auto;
            border-radius: var(--border-radius);
            background-color: rgba(255, 255, 255, 0.05);
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 1000px;
        }

        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        th {
            background-color: rgba(67, 97, 238, 0.2);
            font-weight: 600;
            color: var(--accent);
        }

        tr:hover {
            background-color: rgba(255, 255, 255, 0.05);
        }

        .status-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-active {
            background-color: rgba(76, 175, 80, 0.2);
            color: var(--success);
        }

        .status-inactive {
            background-color: rgba(244, 67, 54, 0.2);
            color: var(--danger);
        }

        .actions {
            display: flex;
            gap: 8px;
        }

        .action-btn {
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            border: none;
            background-color: rgba(255, 255, 255, 0.1);
            color: var(--light);
            cursor: pointer;
            transition: var(--transition);
        }

        .action-btn:hover {
            background-color: var(--accent);
        }

        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 10px 20px;
            border-radius: var(--border-radius);
            border: none;
            cursor: pointer;
            font-weight: 500;
            transition: var(--transition);
        }

        .btn i {
            margin-right: 8px;
        }

        .btn-primary {
            background-color: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background-color: var(--secondary);
        }

        .btn-success {
            background-color: var(--success);
            color: white;
        }

        .btn-warning {
            background-color: var(--warning);
            color: white;
        }

        .btn-danger {
            background-color: var(--danger);
            color: white;
        }

        .btn-outline {
            background-color: transparent;
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: rgba(255, 255, 255, 0.7);
        }

        .btn-outline:hover {
            background-color: rgba(255, 255, 255, 0.1);
            color: var(--light);
        }

        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .spinner {
            width: 24px;
            height: 24px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: var(--accent);
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* 模态框样式 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.7);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        .modal {
            background-color: var(--dark);
            width: 90%;
            max-width: 800px;
            border-radius: var(--border-radius);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            overflow: hidden;
        }

        .modal-header {
            padding: 20px;
            background-color: rgba(67, 97, 238, 0.2);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--accent);
        }

        .modal-close {
            background: none;
            border: none;
            color: var(--light);
            font-size: 20px;
            cursor: pointer;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: var(--transition);
        }

        .modal-close:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .modal-body {
            padding: 20px;
            max-height: 70vh;
            overflow-y: auto;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            opacity: 0.9;
        }

        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 12px 15px;
            background-color: rgba(255, 255, 255, 0.08);
            border: none;
            border-radius: var(--border-radius);
            color: var(--light);
        }

        .form-group textarea {
            height: 100px;
            resize: vertical;
        }

        .form-group input:focus, .form-group select:focus, .form-group textarea:focus {
            outline: none;
            background-color: rgba(255, 255, 255, 0.12);
        }

        .modal-footer {
            padding: 15px 20px;
            background-color: rgba(255, 255, 255, 0.05);
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        /* 响应式设计 */
        @media (max-width: 992px) {
            .sidebar {
                width: 80px;
            }

            .logo-text, .link-text {
                display: none;
            }

            .nav-links a {
                justify-content: center;
            }

            .nav-links a i {
                margin-right: 0;
                font-size: 20px;
            }

            .main-content {
                margin-left: 80px;
            }

            .filters {
                flex-direction: column;
            }
        }

        @media (max-width: 768px) {
            .search-box input {
                width: 150px;
            }

            .search-box input:focus {
                width: 180px;
            }

            .header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }

            .user-actions {
                width: 100%;
                justify-content: space-between;
            }

            .action-bar {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }
        }

        /* 新增样式：表单验证提示 */
        .validation-message {
            color: var(--danger);
            font-size: 12px;
            margin-top: 5px;
            height: 18px;
        }

        .required-field::after {
            content: " *";
            color: var(--danger);
        }

        /* API状态提示 */
        .api-status {
            padding: 10px;
            border-radius: var(--border-radius);
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .api-status.success {
            background-color: rgba(76, 175, 80, 0.2);
            border-left: 4px solid var(--success);
        }

        .api-status.error {
            background-color: rgba(244, 67, 54, 0.2);
            border-left: 4px solid var(--danger);
        }

        .api-status i {
            font-size: 18px;
        }
    </style>
</head>
<body>
<!-- 侧边导航 -->
<div class="sidebar">
    <div class="logo-container">
        <div class="logo">
            <i class="fas fa-brain"></i>
        </div>
        <div class="logo-text">智能CRM</div>
    </div>

    <ul class="nav-links">
        <li><a href="/main"><i class="fas fa-home"></i> <span class="link-text">AI助手</span></a></li>
        <li><a href="/customer" class="active"><i class="fas fa-users"></i> <span class="link-text">客户管理</span></a></li>
        <li><a href="/base_dict"><i class="fas fa-book"></i> <span class="link-text">数据字典</span></a></li>
        <li><a href="/usermanage"><i class="fas fa-user-cog"></i> <span class="link-text">用户管理</span></a></li>
        <li><a href="/product"><i class="fas fa-box"></i> <span class="link-text">产品管理</span></a></li>
        <li><a href="/orderitems"><i class="fas fa-shopping-cart"></i> <span class="link-text">订单管理</span></a></li>
    </ul>
</div>

<!-- 主内容区 -->
<div class="main-content" id="app">
    <!-- 头部区域 -->
    <div class="header">
        <div class="page-title">
            <i class="fas fa-users"></i> 客户管理
        </div>

        <div class="user-actions">
            <div class="user-profile">
                <img src="https://randomuser.me/api/portraits/men/32.jpg" alt="用户头像">
                <span th:text="${session.username}"></span>
            </div>
        </div>
    </div>

    <!-- API状态提示 -->
    <div v-if="apiStatus.message" class="api-status" :class="apiStatus.type">
        <i :class="apiStatus.icon"></i>
        <span>{{ apiStatus.message }}</span>
    </div>

    <!-- 客户管理区域 -->
    <div class="customer-management">
        <div class="action-bar">
            <h2><i class="fas fa-users"></i> 客户列表</h2>
            <button class="btn btn-primary" @click="openAddModal">
                <i class="fas fa-plus"></i> 添加新客户
            </button>
        </div>

        <!-- 筛选区域 -->
        <div class="filters">
            <div class="filter-group">
                <label>客户类型</label>
                <select v-model="filters.cust_type" @change="applyFilters">
                    <option value="">全部类型</option>
                    <option v-for="type in customerTypes" :value="type">{{ type }}</option>
                </select>
            </div>

            <div class="filter-group">
                <label>客户来源</label>
                <select v-model="filters.cust_source" @change="applyFilters">
                    <option value="">全部来源</option>
                    <option v-for="source in customerSources" :value="source">{{ source }}</option>
                </select>
            </div>

            <div class="filter-group">
                <label>客户行业</label>
                <select v-model="filters.cust_industry" @change="applyFilters">
                    <option value="">全部行业</option>
                    <option v-for="industry in customerIndustries" :value="industry">{{ industry }}</option>
                </select>
            </div>

            <div class="filter-group">
                <label>客户级别</label>
                <select v-model="filters.cust_level" @change="applyFilters">
                    <option value="">全部级别</option>
                    <option v-for="level in customerLevels" :value="level">{{ level }}</option>
                </select>
            </div>
            <div class="search-container">
                <label>搜索：</label>
                <div class="search-box">
                    <i class="fas fa-search"></i>
                    <input type="text" v-model="searchQuery" placeholder="搜索客户..." @input="searchCustomers">
                </div>
            </div>

        </div>

        <!-- 客户表格 -->
        <div class="card">
            <div class="table-container">
                <table>
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>客户名称</th>
                        <th>类型</th>
                        <th>来源</th>
                        <th>行业</th>
                        <th>级别</th>
                        <th>联系人</th>
                        <th>电话</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-if="loading">
                        <td colspan="10" class="loading">
                            <div class="spinner"></div>
                            <span>加载客户数据中...</span>
                        </td>
                    </tr>
                    <tr v-else-if="filteredCustomers.length === 0">
                        <td colspan="10" style="text-align: center; padding: 30px;">
                            没有找到匹配的客户
                        </td>
                    </tr>
                    <tr v-for="customer in paginatedCustomers" :key="customer.cust_id">
                        <td>{{ customer.cust_id }}</td>
                        <td>{{ customer.cust_name }}</td>
                        <td>{{ customer.cust_type }}</td>
                        <td>{{ customer.cust_source }}</td>
                        <td>{{ customer.cust_industry }}</td>
                        <td>{{ customer.cust_level }}</td>
                        <td>{{ customer.cust_linkman }}</td>
                        <td>{{ customer.cust_phone || customer.cust_mobile }}</td>
                        <td>{{customer.cust_remark}}</td>
                        <td>
                            <div class="actions">
                                <button class="action-btn" @click="openEditModal(customer)">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="action-btn" @click="deleteCustomer(customer.cust_id)">
                                    <i class="fas fa-trash"></i>
                                </button>
                                <button class="action-btn" @click="viewDetails(customer)">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 分页控件 -->
        <div class="pagination" v-if="filteredCustomers.length > 0" style="display: flex; justify-content: center; align-items: center; margin-top: 20px;">
            <button class="btn btn-outline" :disabled="currentPage === 1" @click="prevPage">
                <i class="fas fa-chevron-left"></i> 上一页
            </button>
            <span style="margin: 0 15px;">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
            <button class="btn btn-outline" :disabled="currentPage === totalPages" @click="nextPage">
                下一页 <i class="fas fa-chevron-right"></i>
            </button>
        </div>
    </div>

    <!-- 添加/编辑客户模态框 -->
    <div class="modal-overlay" v-if="showModal" @click.self="closeModal">
        <div class="modal" @click.stop>
            <div class="modal-header">
                <div class="modal-title">
                    <i class="fas" :class="{'fa-user-plus': isAdding, 'fa-user-edit': !isAdding}"></i>
                    {{ isAdding ? '添加新客户' : '编辑客户信息' }}
                </div>
                <button class="modal-close" @click="closeModal">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <div class="form-grid">
                    <div class="form-group">
                        <label class="required-field">客户名称</label>
                        <input type="text" v-model="currentCustomer.cust_name" placeholder="输入客户名称">
                        <div class="validation-message" v-if="errors.cust_name">{{ errors.cust_name }}</div>
                    </div>
                    <div class="form-group">
                        <label class="required-field">客户类型</label>
                        <select v-model="currentCustomer.cust_type">
                            <option v-for="type in customerTypes" :value="type">{{ type }}</option>
                        </select>
                        <div class="validation-message" v-if="errors.cust_type">{{ errors.cust_type }}</div>
                    </div>
                    <div class="form-group">
                        <label class="required-field">客户来源</label>
                        <select v-model="currentCustomer.cust_source">
                            <option v-for="source in customerSources" :value="source">{{ source }}</option>
                        </select>
                        <div class="validation-message" v-if="errors.cust_source">{{ errors.cust_source }}</div>
                    </div>
                    <div class="form-group">
                        <label class="required-field">所属行业</label>
                        <select v-model="currentCustomer.cust_industry">
                            <option v-for="industry in customerIndustries" :value="industry">{{ industry }}</option>
                        </select>
                        <div class="validation-message" v-if="errors.cust_industry">{{ errors.cust_industry }}</div>
                    </div>
                    <div class="form-group">
                        <label class="required-field">客户级别</label>
                        <select v-model="currentCustomer.cust_level">
                            <option v-for="level in customerLevels" :value="level">{{ level }}</option>
                        </select>
                        <div class="validation-message" v-if="errors.cust_level">{{ errors.cust_level }}</div>
                    </div>
                    <div class="form-group">
                        <label class="required-field">联系人</label>
                        <input type="text" v-model="currentCustomer.cust_linkman" placeholder="输入联系人姓名">
                        <div class="validation-message" v-if="errors.cust_linkman">{{ errors.cust_linkman }}</div>
                    </div>
                    <div class="form-group">
                        <label>联系电话</label>
                        <input type="text" v-model="currentCustomer.cust_phone" placeholder="输入固定电话">
                    </div>
                    <div class="form-group">
                        <label class="required-field">手机号码</label>
                        <input type="text" v-model="currentCustomer.cust_mobile" placeholder="输入手机号码">
                        <div class="validation-message" v-if="errors.cust_mobile">{{ errors.cust_mobile }}</div>
                    </div>
                    <div class="form-group">
                        <label>电子邮箱</label>
                        <input type="email" v-model="currentCustomer.cust_email" placeholder="输入电子邮箱">
                    </div>
                    <div class="form-group">
                        <label>客户地址</label>
                        <input type="text" v-model="currentCustomer.cust_address" placeholder="输入客户地址">
                    </div>
                    <div class="form-group">
                        <label>备注</label>
                        <textarea v-model="currentCustomer.cust_remark" placeholder="输入备注信息"></textarea>
                    </div>
<!--                    <div class="form-group">-->
<!--                        <label>状态</label>-->
<!--                        <select v-model="currentCustomer.active">-->
<!--                            <option :value="true">活跃</option>-->
<!--                            <option :value="false">非活跃</option>-->
<!--                        </select>-->
<!--                    </div>-->
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline" @click="closeModal">取消</button>
                <button class="btn btn-primary" @click="saveCustomer" :disabled="saving">
                    <template v-if="saving">
                        <i class="fas fa-spinner fa-spin"></i> 处理中...
                    </template>
                    <template v-else>
                        <i class="fas fa-save"></i> {{ isAdding ? '添加客户' : '保存更改' }}
                    </template>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    const CUSTOMER_API_BASE = '/api/customers'; // 确保与后端路径匹配

    new Vue({
        el: '#app',
        data: {
            userId: 'user_' + Math.floor(Math.random() * 1000),
            searchQuery: '',
            customers: [],
            filteredCustomers: [],
            loading: true,
            showModal: false,
            isAdding: true,
            currentCustomer: null,
            currentPage: 1,
            itemsPerPage: 10,
            errors: {},
            saving: false,
            apiStatus: {
                message: '',
                type: '',
                icon: ''
            },

            // 筛选条件
            filters: {
                cust_type: '',
                cust_source: '',
                cust_industry: '',
                cust_level: '',
                active: ''
            },

            // 客户数据字典
            customerTypes: ['企业客户', '个人客户', '政府机构', '教育机构', '其他'],
            customerSources: ['线上广告', '线下活动', '客户推荐', '社交媒体', '搜索引擎', '展会活动'],
            customerIndustries: ['互联网', '金融', '教育', '医疗健康', '制造业', '零售', '房地产', '其他'],
            customerLevels: ['VIP客户', '重要客户', '普通客户', '潜在客户']
        },
        computed: {
            totalPages() {
                return Math.ceil(this.filteredCustomers.length / this.itemsPerPage);
            },
            paginatedCustomers() {
                const start = (this.currentPage - 1) * this.itemsPerPage;
                const end = start + this.itemsPerPage;
                return this.filteredCustomers.slice(start, end);
            }
        },
        mounted() {
            this.fetchCustomers();
            window.addEventListener('keydown', this.handleKeydown);
        },
        beforeDestroy() {
            window.removeEventListener('keydown', this.handleKeydown);
        },
        methods: {
            handleKeydown(e) {
                if (e.key === 'Escape' && this.showModal) {
                    this.closeModal();
                }
            },

            // 显示API操作状态
            showApiStatus(message, type = 'success') {
                this.apiStatus = {
                    message,
                    type,
                    icon: type === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle'
                };

                // 3秒后自动清除状态
                setTimeout(() => {
                    this.apiStatus.message = '';
                }, 3000);
            },

            fetchCustomers() {
                axios.get(CUSTOMER_API_BASE+"/allcustomer")
                    .then(response => {
                        this.customers = response.data;
                        this.filteredCustomers = [...this.customers];
                        this.loading = false;
                    })
                    .catch(error => {
                        console.error('获取客户列表失败:', error);
                        this.loading = false;
                        this.showApiStatus('获取客户列表失败，请重试', 'error');
                    });
            },

            // 搜索客户
            searchCustomers() {
                if (!this.searchQuery) {
                    this.filteredCustomers = [...this.customers];
                    this.currentPage = 1;
                    return;
                }

                const query = this.searchQuery.toLowerCase();
                this.filteredCustomers = this.customers.filter(customer =>
                    customer.cust_name.toLowerCase().includes(query) ||
                    customer.cust_linkman.toLowerCase().includes(query) ||
                    (customer.cust_mobile && customer.cust_mobile.includes(query)) ||
                    (customer.cust_phone && customer.cust_phone.includes(query)) ||
                    (customer.cust_email && customer.cust_email.toLowerCase().includes(query))
                );
                this.currentPage = 1;
            },

            // 应用筛选
            applyFilters() {
                this.filteredCustomers = this.customers.filter(customer => {
                    return (
                        (!this.filters.cust_type || customer.cust_type === this.filters.cust_type) &&
                        (!this.filters.cust_source || customer.cust_source === this.filters.cust_source) &&
                        (!this.filters.cust_industry || customer.cust_industry === this.filters.cust_industry) &&
                        (!this.filters.cust_level || customer.cust_level === this.filters.cust_level) &&
                        (
                            this.filters.active === '' ||
                            (this.filters.active === 'active' && customer.active) ||
                            (this.filters.active === 'inactive' && !customer.active)
                        )
                    );
                });
                this.currentPage = 1;
            },

            // 打开添加模态框
            openAddModal() {
                this.currentCustomer = this.getEmptyCustomer();
                this.isAdding = true;
                this.showModal = true;
                this.errors = {};
            },

            // 打开编辑模态框
            openEditModal(customer) {
                this.currentCustomer = {...customer};
                this.isAdding = false;
                this.showModal = true;
                this.errors = {};
            },

            // 关闭模态框
            closeModal() {
                this.showModal = false;
                this.errors = {};
            },

            // 验证客户数据
            validateCustomer() {
                this.errors = {};
                let isValid = true;

                if (!this.currentCustomer.cust_name) {
                    this.errors.cust_name = '客户名称不能为空';
                    isValid = false;
                }

                if (!this.currentCustomer.cust_type) {
                    this.errors.cust_type = '请选择客户类型';
                    isValid = false;
                }

                if (!this.currentCustomer.cust_source) {
                    this.errors.cust_source = '请选择客户来源';
                    isValid = false;
                }

                if (!this.currentCustomer.cust_industry) {
                    this.errors.cust_industry = '请选择所属行业';
                    isValid = false;
                }

                if (!this.currentCustomer.cust_level) {
                    this.errors.cust_level = '请选择客户级别';
                    isValid = false;
                }

                if (!this.currentCustomer.cust_linkman) {
                    this.errors.cust_linkman = '联系人不能为空';
                    isValid = false;
                }

                if (!this.currentCustomer.cust_mobile) {
                    this.errors.cust_mobile = '手机号码不能为空';
                    isValid = false;
                } else if (!/^1[3-9]\d{9}$/.test(this.currentCustomer.cust_mobile)) {
                    this.errors.cust_mobile = '请输入有效的手机号码';
                    isValid = false;
                }

                return isValid;
            },

            saveCustomer() {
                if (!this.validateCustomer()) return;

                this.saving = true;
                const method = this.isAdding ? 'post' : 'put';
                const url = this.isAdding
                    ? CUSTOMER_API_BASE
                    : `${CUSTOMER_API_BASE}/${this.currentCustomer.cust_id}`;

                // 准备要发送的数据
                const requestData = {...this.currentCustomer};

                // 移除前端生成的临时ID（如果存在）
                if (this.isAdding) {
                    delete requestData.cust_id;
                }

                axios[method](url, requestData)
                    .then(response => {
                        this.saving = false;
                        this.fetchCustomers(); // 刷新数据
                        this.showModal = false;
                        const action = this.isAdding ? '添加' : '更新';
                        this.showApiStatus(`客户 ${this.currentCustomer.cust_name} 已成功${action}！`);
                    })
                    .catch(error => {
                        console.error(`${this.isAdding ? '添加' : '更新'}客户失败:`, error);
                        this.saving = false;
                        let errorMsg = `${this.isAdding ? '添加' : '更新'}客户失败`;
                        if (error.response && error.response.data) {
                            errorMsg = error.response.data.message || errorMsg;
                        }
                        this.showApiStatus(errorMsg, 'error');
                    });
            },

            // 删除客户
            deleteCustomer(id) {
                const customer = this.customers.find(c => c.cust_id === id);
                if (!customer || !confirm(`确定要删除客户 ${customer.cust_name} 吗？`)) return;

                axios.delete(`${CUSTOMER_API_BASE}/${id}`)
                    .then(() => {
                        this.fetchCustomers(); // 刷新数据
                        this.showApiStatus(`客户 ${customer.cust_name} 已删除！`);
                    })
                    .catch(error => {
                        console.error('删除客户失败:', error);
                        let errorMsg = '删除客户失败';
                        if (error.response && error.response.data) {
                            errorMsg = error.response.data.message || errorMsg;
                        }
                        this.showApiStatus(errorMsg, 'error');
                    });
            },

            // 查看客户详情
            viewDetails(customer) {
                alert(`查看客户详情: ${customer.cust_name}\n联系人: ${customer.cust_linkman}\n电话: ${customer.cust_phone || customer.cust_mobile}\n地址: ${customer.cust_address || '无'}`);
            },

            // 获取空客户对象
            getEmptyCustomer() {
                return {
                    cust_id: null, // 后端会自动生成ID
                    cust_name: '',
                    cust_type: '',
                    cust_source: '',
                    cust_industry: '',
                    cust_level: '',
                    cust_linkman: '',
                    cust_phone: '',
                    cust_mobile: '',
                    cust_email: '',
                    cust_address: '',
                    cust_remark: '',
                    user_id: 1,
                    create_time: new Date(),
                    update_time: new Date(),
                    active: true
                };
            },

            // 分页方法
            nextPage() {
                if (this.currentPage < this.totalPages) {
                    this.currentPage++;
                }
            },

            prevPage() {
                if (this.currentPage > 1) {
                    this.currentPage--;
                }
            }
        }
    });
</script>
</body>
</html>